package com.flycent.hqhs.ui;

import java.util.HashMap;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.UserBaseInfo;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.util.ContextUtil;
import com.flycent.hqhs.util.PreferenceUtil;

/**
 *  登录
 */
public class LoginActivity extends BackableTitleBarActivity implements PlatformActionListener {
	@ViewInject(id = R.id.username) private EditText userNameEdit;
	@ViewInject(id = R.id.password) private EditText userPwdEdit;
	@ViewInject(id = R.id.login_name_delete_img , click = "butClick") ImageView mNameDeleteImg;
	@ViewInject(id = R.id.login_pass_delete_img , click = "butClick") ImageView mPassDeleteImg;

	private String mUserNameStr;
	//	private String mPassWordStr;

	//为了必要时候从其他的Activity中finish这个
	public static LoginActivity instance = null;
	private UserBaseInfo user;

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_login);
		getTitleBar().setTitle(R.string.title_login);
		FinalActivity.initInjectedView(this);
		instance = this;

		if (null != (user = PreferenceUtil.getUser(this))){
			System.out.println("user=="+user);
			mUserNameStr = user.getUsername();
			//			mPassWordStr = user.getUserpass();
			userNameEdit.setText(mUserNameStr);
			//userPwdEdit.setText(mPassWordStr);	
		}
		showDeleteImage();

	}

	private void showDeleteImage() {

		userNameEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(!hasFocus){
					mNameDeleteImg.setVisibility(View.GONE);
				}else {
					if(invalidateText(userNameEdit))
						mNameDeleteImg.setVisibility(View.GONE);
					else 
						mNameDeleteImg.setVisibility(View.VISIBLE);
				}
			}
		});

		userNameEdit.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				if(!invalidateText(userNameEdit)){
					mNameDeleteImg.setVisibility(View.VISIBLE);
				}else {
					mNameDeleteImg.setVisibility(View.GONE);
				}
			}
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}
			@Override
			public void afterTextChanged(Editable arg0) {
			}
		});

		mNameDeleteImg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				userNameEdit.setText("");
			}
		});

		userPwdEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if(!hasFocus){
					mPassDeleteImg.setVisibility(View.GONE);
				}else {
					if(invalidateText(userPwdEdit))
						mPassDeleteImg.setVisibility(View.GONE);
					else 
						mPassDeleteImg.setVisibility(View.VISIBLE);
				}
			}
		});

		userPwdEdit.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				if(!invalidateText(userPwdEdit)){
					mPassDeleteImg.setVisibility(View.VISIBLE);
				}else {
					mPassDeleteImg.setVisibility(View.GONE);
				}
			}
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}
			@Override
			public void afterTextChanged(Editable arg0) {
			}
		});

		mPassDeleteImg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				userPwdEdit.setText("");
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.text_forget_pwd: 	// 忘记密码
			ContextUtil.startActivity(this, ForgotPwdActivity.class);;

			break;
		case R.id.text_register: 	// 注册
			ContextUtil.startActivity(this, RegisterActivity.class);;

			break;
		case R.id.btn_login: 		// 登录
			if(invalidateText(userNameEdit, R.string.info_please_input_user_no) || invalidateText(userPwdEdit, R.string.info_please_input_pwd_no))
				return;
			login(getText(userNameEdit), getText(userPwdEdit), null);
			break;
		case R.id.btn_qq_login: 	// qq登录
			authorize(new QQ(this));
			break;
		case R.id.btn_sina_login: 	// sina登录	
			authorize(new SinaWeibo(this));
			break;	
		default:
			break;
		}
	}


	/** 登录 @param plat 非第三方平台传null */
	private void login(final String username, final String password, final Platform plat) {
		new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {
				WebClient client = WebClient.getInstance(LoginActivity.this);
				try {
					//					RSAkey key = client.publicKey();
					// String enPassword = StringUtil.encryptByRSA(password, key); // 加密
					UserBaseInfo user = client.login(username, password);
					user.setUserpass(password);

					// 登录成功
					if (null != plat) user.setPlatformName(plat.getName()); // 第三方
					PreferenceUtil.setUser(LoginActivity.this, user);
					
					setResult(200);
					finish();
					// ...

				} catch (WebException e) {
					// 第三方登录，账户未注册
					if (null != plat && "shop.login.unknownAccount".equals(e.getStatusCode())) {
						try {
							// 注册
							client.checkUsername(username);
							client.register(getMyUUID(), null, username, password);
							// 登录
							login(username, password, null);

						} catch (WebException e1) {
							e1.printStackTrace();
						}
					} else
						e.printStackTrace(); 					// 其他登录错误
				}

				return null;
			}

		}.execute();
	}

	/** 授权，注销时：plat.removeAccount()，取消授权 */
	private void authorize(Platform plat) {
		if(plat.isValid()) { 							// 授权有效
			String userId = plat.getDb().getUserId();
			App.showLog("userId=="+userId);
			if (!TextUtils.isEmpty(userId)) {
				// 登录(如果未注册，则须调用注册接口注册，再进行登录)
				login(userId, userId, plat);
				return;
			}
		}
		plat.setPlatformActionListener(this);
		plat.SSOSetting(true);
		// plat.authorize();
		plat.showUser(null); // 会显示资料
	}


	@Override
	public void onComplete(Platform paramPlatform, int paramInt, HashMap<String, Object> paramHashMap) {
		String userId = paramPlatform.getDb().getUserId();
		App.showLog(paramHashMap);

		// 登录(如果未注册，则须调用注册接口注册，再进行登录)
		login(userId, userId, paramPlatform);
	}

	@Override
	public void onError(Platform paramPlatform, int paramInt, Throwable paramThrowable) {
		App.showShortToast(R.string.auth_error);

		paramPlatform.removeAccount();  // 删除错误的授权
		paramThrowable.printStackTrace();
	}

	@Override
	public void onCancel(Platform paramPlatform, int paramInt) {}
}
